package com.xiaoming.config;

import com.xiaoming.bean.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.util.Objects;

/**
 * @author xiaoming
 * @date 2021-04-13 22:27
 */
@Configuration
public class MyRedisConfig {
    @Bean(name = {"employeeRedisTemplate"})
    /** 自定义  employee redisTemplate */
    public RedisTemplate<Object, Employee> employeeRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Employee> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用 jackson 实现JSON 序列化
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }

//    @Primary // 多个时, 需要指定主 CacheManager
    @Bean
    /** 自定义 CacheManager */
    public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> employeeRedisTemplate) {

        return new RedisCacheManager(
                // RedisCache  Writer
                RedisCacheWriter
                        .nonLockingRedisCacheWriter(Objects
                                .requireNonNull(employeeRedisTemplate
                                        .getConnectionFactory())),
                /// RedisCache 配置类
                RedisCacheConfiguration
                        .defaultCacheConfig()
                        .serializeValuesWith(RedisSerializationContext
                                .fromSerializer(new Jackson2JsonRedisSerializer<Employee>(Employee.class))
                                .getValueSerializationPair())
                        // 禁用前缀
                        .disableCachingNullValues()
        );
    }

}
